package com.vm.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.adapter.FragAdapter;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.db.LocalUserInfoDao;
import com.vm.db.UpgradeSoftDao;
import com.vm.fragment.ActiveFragment;
import com.vm.fragment.CategoryFragment;
import com.vm.fragment.FoundFragment;
import com.vm.fragment.IndexFragment;
import com.vm.fragment.MallFragment;
import com.vm.fragment.ManagerFragment;
import com.vm.model.LocalUserInfo;
import com.vm.model.Soft;
import com.vm.model.UpgradeSoft;
import com.vm.myview.SlidingMenu;
import com.vm.utils.DownloadThread;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.vm.utils.SocketHttpRequester;
import com.vm.utils.UpgradeUtil;
import com.wwt.app.R;

import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

@SuppressLint("NewApi")
public class MainTabActivity extends FragmentActivity {

	private SlidingMenu mMenu;
	protected static final String TAG = "MainActivity";

	FoundFragment foundFragment;
	CategoryFragment categoryFragment;
	MallFragment mallFragment;

	private ViewPager vp;
	private FragAdapter adapter;

	Button btn_index;
	Button btn_category;
	Button btn_main;

	Button btn_software_upgrade_number;
	RadioGroup main_radiogroup;

	RequestQueue mQueue;
	ImageButton imgbtn_search;
	ImageButton imgbtn_download_manager;
	ImageView iv_logo;

	LocalUserInfo localUserInfo;
	static LocalUserInfoDao luidao;

	Soft soft;
	String versionName;
	DownInfoDao dao;

	List<Fragment> fragments;
	private DownloadThread downThread;
	private Handler downHandler;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mMenu = (SlidingMenu) findViewById(R.id.id_menu);

		luidao = new LocalUserInfoDao(this);
		DownInfoDao downInfoDao = new DownInfoDao(this);
		downInfoDao.stopAll();

		UpgradeUtil upgradeUtil = new UpgradeUtil(this);
		upgradeUtil.getNew();
		// UpgradeUtil.getNew(this);
		mQueue = MyVolley.getRequestQueue();

		// 初始化用户信息
		initView();
		initUserInfo();
		getVersion();
		getNewVersion();
		initData();
		getMyDeviceId();

		dao = new DownInfoDao(this);
		boolean isNetwork = false;
		// NetworkUtil networkUtil = new NetworkUtil();
		isNetwork = isOpenNetwork();

		if (isNetwork) {
			// 执行相关操作
		} else {
			Toast.makeText(getApplicationContext(), "亲，网络连了么？",
					Toast.LENGTH_LONG).show();
		}

		// 初始化导航单选按钮监听
		initRbtnListener();

		UpgradeSoftDao dao = new UpgradeSoftDao(this);

		List<UpgradeSoft> appList = dao.getUpgradeSofts();

		// 好啦 这下手机上安装的应用数据都存在appList里了。
		if (appList.size() > 0) {

			btn_software_upgrade_number
					.setText(Integer.toString(appList.size()));
			btn_software_upgrade_number.setVisibility(View.VISIBLE);
		}

		upgradeUtil = null;
		downInfoDao = null;
		dao = null;
		appList = null;

	}

	ImageButton ibtn_modify;
	RelativeLayout rlayout_login; // 登录注册
	RelativeLayout rlayout_account; // 账户名
	TextView tv_login; // 登录
	TextView tv_register; // 注册
	TextView tv_account; // 账户名
	LinearLayout layout_get_points;
	LinearLayout layout_order;
	LinearLayout rlayout_address;
	LinearLayout layout_collection;
	Button btn_exit;
	TextView tv_intergral;

	private void initView() {
		ibtn_modify = (ImageButton) findViewById(R.id.ibtn_modify);
		rlayout_login = (RelativeLayout) findViewById(R.id.rlayout_login);
		rlayout_account = (RelativeLayout) findViewById(R.id.rlayout_account);
		tv_login = (TextView) findViewById(R.id.tv_login);
		tv_register = (TextView) findViewById(R.id.tv_register);
		tv_account = (TextView) findViewById(R.id.tv_account);
		btn_exit = (Button) findViewById(R.id.btn_exit);

		tv_intergral = (TextView) findViewById(R.id.tv_intergral);
		layout_get_points = (LinearLayout) findViewById(R.id.layout_get_points);
		layout_order = (LinearLayout) findViewById(R.id.layout_order);
		rlayout_address = (LinearLayout) findViewById(R.id.layout_address);
		layout_collection = (LinearLayout) findViewById(R.id.layout_collection);
		
		layout_get_points.setOnClickListener(menuItemListener);
		layout_order.setOnClickListener(menuItemListener);
		rlayout_address.setOnClickListener(menuItemListener);
		layout_collection.setOnClickListener(menuItemListener);
	}

	public void toggleMenu(View view) {
		mMenu.toggle();
	}

	private void initData() {
		fragments = new ArrayList<Fragment>();
		fragments.add(new IndexFragment());
		fragments.add(new CategoryFragment());
		fragments.add(new MallFragment());
		fragments.add(new ActiveFragment());
		fragments.add(new ManagerFragment());
		vp = (ViewPager) findViewById(R.id.viewpager);
		adapter = new FragAdapter(getSupportFragmentManager(), fragments);
		vp.setAdapter(adapter);

		// 设置最大缓存数
		// 默认缓存2个页面,当出现第三个页面会删掉之前缓存中的一个.
		vp.setOffscreenPageLimit(5);
		vp.setCurrentItem(0);

		// fm = getSupportFragmentManager();// 获取fragment管理工具类
		// replace(new FoundFragment());
	}
	
	OnClickListener menuItemListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			switch (v.getId()) {
			case R.id.layout_get_points:
				intent = new Intent(MainTabActivity.this,IntergralActivity.class);
				startActivity(intent);
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 
	 */
	private void initUserInfo() {
		localUserInfo = luidao.query();
		if (localUserInfo != null) {
			CurrentUser.USERID = localUserInfo.getUserId();
			CurrentUser.USERNAME = localUserInfo.getUsername();
			CurrentUser.INTERGRAL = localUserInfo.getIntergral();
			CurrentUser.IMAGEURL = localUserInfo.getImageUrl();
		}
		localUserInfo = null;

	}

	/**
	 * 个人设置监听
	 */
	private OnClickListener personalListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			switch (v.getId()) {
			case R.id.tv_login:
				LoginActivity.mainHandler = mainHandler;
				intent = new Intent(MainTabActivity.this, LoginActivity.class);
				startActivity(intent);
				break;
			case R.id.tv_register:
				intent = new Intent(MainTabActivity.this,
						RegisterActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_exit:
				luidao.delete();
				rlayout_login.setVisibility(View.VISIBLE);
				rlayout_account.setVisibility(View.GONE);
				btn_exit.setVisibility(View.INVISIBLE);
				tv_login.setOnClickListener(personalListener);
				tv_register.setOnClickListener(personalListener);
				break;

			default:
				break;
			}

		}
	};

	/**
	 * 搜索按钮监听
	 */
	public OnClickListener searchClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MainTabActivity.this,
					SearchActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * 初始化导航单选按钮监听
	 */
	public void initRbtnListener() {
		// 获取单选按钮group,并设置监听事件

		btn_software_upgrade_number = (Button) findViewById(R.id.btn_software_upgrade_number);

		main_radiogroup = (RadioGroup) findViewById(R.id.main_radiogroup);
		main_radiogroup.setOnCheckedChangeListener(group_listener);

		imgbtn_search = (ImageButton) findViewById(R.id.imgbtn_search);
		imgbtn_search.setOnClickListener(searchClickListener);

		imgbtn_download_manager = (ImageButton) findViewById(R.id.imgbtn_download_manager);
		imgbtn_download_manager.setOnClickListener(downClickListener);

		localUserInfo = luidao.query();
		if (localUserInfo != null) {
			// 给用户常量赋值
			CurrentUser.USERID = localUserInfo.getUserId();
			CurrentUser.USERNAME = localUserInfo.getUsername();
			CurrentUser.INTERGRAL = localUserInfo.getIntergral();
			CurrentUser.IMAGEURL = localUserInfo.getImageUrl();

			// 加载头像
			iv_logo = (ImageView) findViewById(R.id.iv_logo);

			updateLogo(iv_logo);

			rlayout_login.setVisibility(View.GONE);
			rlayout_account.setVisibility(View.VISIBLE);
			tv_account.setText(CurrentUser.USERNAME);

			tv_intergral.setText(Integer.toString(CurrentUser.INTERGRAL));

			btn_exit.setOnClickListener(personalListener);
			// iv_logo.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// // 传递参数,加载头像
			// new SocketHttpRequester(MainTabActivity.this, mainHandler);
			// if (CurrentUser.USERID != null) {
			// // 给用户常量赋值
			// Intent intent = new Intent(MainTabActivity.this,
			// PersonCenterActivity.class);
			// startActivity(intent);
			// } else {
			// // 传递线程参数给登录窗口
			// LoginActivity.mainHandler = mainHandler;
			// Intent intent = new Intent(MainTabActivity.this,
			// UserInfoActivity.class);
			// startActivity(intent);
			// }
			//
			// }
			// });

		} else {
			rlayout_login.setVisibility(View.VISIBLE);
			rlayout_account.setVisibility(View.GONE);
			btn_exit.setVisibility(View.INVISIBLE);
			tv_login.setOnClickListener(personalListener);
			tv_register.setOnClickListener(personalListener);
		}

		localUserInfo = null;

	}

	OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MainTabActivity.this,
					DownloadManageActivity.class);
			startActivity(intent);
			intent = null;
		}
	};

	@SuppressWarnings("deprecation")
	public void updateLogo(ImageView iv_logo) {

		if (CurrentUser.IMAGEURL != null) {
			ImageLoader.getInstance().displayImage(
					VMConst.URL + CurrentUser.IMAGEURL, iv_logo,
					MyDisplayImageOptions.getInstance());
		} else {
			iv_logo.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.bg_photo));
			// iv_logo.setBackground(getResources().getDrawable(R.drawable.bg_photo));
		}
	}

	/**
	 * 单选按钮监听
	 */
	public OnCheckedChangeListener group_listener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {

			switch (checkedId) {
			case R.id.rbtn_index:
				vp.setCurrentItem(0);
				break;
			case R.id.rbtn_category:
				vp.setCurrentItem(1);
				break;
			case R.id.rbtn_mall:
				vp.setCurrentItem(2);
				break;
			case R.id.rbtn_activity:
				vp.setCurrentItem(3);
				break;
			case R.id.rbtn_manage:
				vp.setCurrentItem(4);
				break;
			}
		}
	};

	// private Intent getTabItemIntent(int index) {
	// Intent intent = new Intent(this, ConValue.mainTabClass[index]);
	// return intent;
	// }

	/**
	 * 对网络连接状态进行判断
	 * 
	 * @return true, 可用； false， 不可用
	 */
	public boolean isOpenNetwork() {
		ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}
		return false;
	}

	private int keyBackClickCount = 0;

	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyBackClickCount++) {
			case 0:
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						keyBackClickCount = 0;
					}
				}, 3000);
				break;
			case 1:
				this.finish();
				break;
			default:
				break;
			}
			return true;

		}
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 主线程刷新头像
	 */
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				// System.out.println("我回到主线程了");
				updateCurrentLogo();
				break;
			case 1000:

				dao.complete("96f480a8-6911-46f0-a92f-11ea4a42304e");
				File apkfile = new File(StringUtil.getSdApkUrl(soft.getName()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);

				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				MainTabActivity.this.startActivity(i);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 刷新头像
	 */
	public void updateCurrentLogo() {

		try {
			if (CurrentUser.IMAGEURL != null) {
				ImageLoader.getInstance().displayImage(
						VMConst.URL + CurrentUser.IMAGEURL, iv_logo,
						MyDisplayImageOptions.getInstance());

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void getNewVersion() {
		String url = VMConst.DETAIL_URL
				+ "96f480a8-6911-46f0-a92f-11ea4a42304e";
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						// TODO Auto-generated method stub
						soft = JsonUtils.jsonToBean(arg0, Soft.class);
						if (!versionName.equals(soft.getVersion())) {
							final UpdateDialog dialog=new UpdateDialog(MainTabActivity.this,"发现软件有新版本，是否下载？","确认下载","稍后再说");
							dialog.show();
							dialog.setClicklistener(new UpdateDialog.ClickListenerInterface() {
								
								@Override
								public void doConfirm() {
									// TODO Auto-generated method stub
									Toast toast2 = Toast
											.makeText(
													MainTabActivity.this,
													"下载更新文件",
													500);
									toast2.setGravity(
											Gravity.CENTER, 0,
											0);
									toast2.show();
									Message msg = new Message();
									// msg.arg1 = currentId;
									msg.what = 100;
									// 下载地址
									// msg.obj =
									// VMConst.DOWN_URL +
									// currentId + "&userId="
									// + CurrentUser.USERID;

									msg.obj = soft;
									downThread = new DownloadThread(
											MainTabActivity.this,
											mainHandler);
									downThread.start();

									do {
										downHandler = downThread
												.getDownHandler();
									} while (null == downHandler);

									downHandler
											.sendMessage(msg);
									dialog.dismiss();
								}
								
								@Override
								public void doCancel() {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
							//AlertDialog.Builder builder = new AlertDialog.Builder(
//									MainTabActivity.this);
//							builder.setTitle("软件更新")
//									.setMessage("发现软件有新版本，是否下载？")
//									.setCancelable(false)
//									.setPositiveButton(
//											"确认下载",
//											new DialogInterface.OnClickListener() {
//
//												@Override
//												public void onClick(
//														DialogInterface dialog,
//														int which) {
//													// TODO Auto-generated
//													// method stub
//													Toast toast2 = Toast
//															.makeText(
//																	MainTabActivity.this,
//																	"下载更新文件",
//																	500);
//													toast2.setGravity(
//															Gravity.CENTER, 0,
//															0);
//													toast2.show();
//													Message msg = new Message();
//													// msg.arg1 = currentId;
//													msg.what = 100;
//													// 下载地址
//													// msg.obj =
//													// VMConst.DOWN_URL +
//													// currentId + "&userId="
//													// + CurrentUser.USERID;
//
//													msg.obj = soft;
//													downThread = new DownloadThread(
//															MainTabActivity.this,
//															mainHandler);
//													downThread.start();
//
//													do {
//														downHandler = downThread
//																.getDownHandler();
//													} while (null == downHandler);
//
//													downHandler
//															.sendMessage(msg);
//												}
//
//											})
//									.setNegativeButton(
//											"稍后再说",
//											new DialogInterface.OnClickListener() {
//												public void onClick(
//														DialogInterface dialog,
//														int id) {
//													dialog.cancel();
//												}
//											});
//							AlertDialog alert = builder.create();
//							alert.show();
						}
					}

				}, null);
		mQueue.add(jsonObjectRequest);
	}

	// private void replace(Fragment fragment) {
	// FragmentTransaction beginTransaction = fm.beginTransaction();
	// // beginTransaction.setCustomAnimations(android.R.animator.fade_in,
	// // android.R.animator.fade_out);
	// beginTransaction.replace(R.id.main_content, fragment);
	// beginTransaction.commit();
	// }

	// private void show(Fragment fragment) {
	// FragmentTransaction beginTransaction = fm.beginTransaction();
	// beginTransaction.show(fragment);
	//
	// // beginTransaction.hide(arg0);
	// beginTransaction.commit();
	// }

	public void getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			versionName = info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成机器唯一识别码
	 */
	public void getMyDeviceId() {
		TelephonyManager tm = (TelephonyManager) getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		final String tmDevice, tmSerial, androidId;
		tmDevice = tm.getDeviceId();
		tmSerial = tm.getSimSerialNumber();
		androidId = android.provider.Settings.Secure.getString(
				getContentResolver(),
				android.provider.Settings.Secure.ANDROID_ID);
		java.util.UUID deviceUuid = new java.util.UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

		StringUtil.DEVICEID = deviceUuid.toString();
	}
}
